package cn.evilelf.util;

import java.io.File;
import java.io.FileFilter;

import cn.evilelf.util.exceptions.InvalidOptionException;

public class BatchRename {

	private static final String usage = "rename <-i:<input postfix>> "
			+ "[-o:<output postfix>] " + "[-s:<start name>]";

	private static String iPostFix = null;
	private static String oPostFix = null;
	private static int sName = 1;

	public static void main(String[] args) {
		try {
			Options options = new Options(args);
			if (options.containsOption("i")) {
				iPostFix = options.getOptionValue("i");
				if (null == iPostFix)
					throw new InvalidOptionException();
			} else
				throw new InvalidOptionException();
			if (options.containsOption("o")) {
				oPostFix = options.getOptionValue("o");
				if (null == oPostFix)
					throw new InvalidOptionException();
			} else
				oPostFix = iPostFix;
			if (options.containsOption("s")) {
				String strStartName = options.getOptionValue("s");
				if (null == strStartName)
					throw new InvalidOptionException();
				sName = Integer.parseInt(strStartName);
			}
		} catch (Exception e) {
			System.err.println("Invalid options, usage:");
			System.err.println(usage);
			System.err.flush();
			System.exit(1);
		}

		File curDir = new File(".");
		File[] fileArray = curDir.listFiles(new FileFilter() {

			@Override
			public boolean accept(File file) {
				String tmp = file.getName().toLowerCase();
				if (tmp.endsWith(iPostFix)) {
					return true;
				}
				return false;
			}
		});

		boolean isIntegerName = true;
		for (File file : fileArray) {
			try {
				Integer.parseInt(file.getName().substring(0,
						file.getName().indexOf('.')));
			} catch (NumberFormatException e) {
				isIntegerName = false;
			}
			if (!isIntegerName)
				break;
		}

		if (isIntegerName) {
			int[] intFileNameArray = new int[fileArray.length];
			for (int i = 0; i < fileArray.length; ++i) {
				intFileNameArray[i] = Integer.parseInt(fileArray[i].getName()
						.substring(0, fileArray[i].getName().indexOf('.')));
			}

			cn.evilelf.sort.Quick.sort(intFileNameArray);

			for (int i = 0; i < intFileNameArray.length; ++i) {
				File file = new File(curDir, String
						.valueOf(intFileNameArray[i])
						+ "." + iPostFix);
				file.renameTo(new File(curDir, String.valueOf(i + sName) + "."
						+ oPostFix));
			}
		} else {
			cn.evilelf.sort.Quick.sort(fileArray);

			for (File file : fileArray) {
				file.renameTo(new File(curDir, String.valueOf(sName++) + "."
						+ oPostFix));
			}
		}
	}
}
